<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="题目难度" prop="lv">
                <el-input-number
                        style="width: 200px"
                        v-model="queryParams.lv"
                        placeholder="请输入题目难度"
                        :min="0"
                        :max="5"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>
            <!--      <el-form-item label="题目分数" prop="score">-->
            <!--        <el-input-->
            <!--          v-model="queryParams.score"-->
            <!--          placeholder="请输入题目分数"-->
            <!--          clearable-->
            <!--          @keyup.enter="handleQuery"-->
            <!--        />-->
            <!--      </el-form-item>-->
            <el-form-item label="题目类型" prop="questionType">
                <el-select v-model="queryParams.questionType" placeholder="请选择题目类型" clearable>
                    <el-option
                            v-for="dict in business_question_type"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="题目分类" prop="questionCategoryId">
                <el-select v-model="queryParams.questionCategoryId" placeholder="请选择题目分类" clearable>
                    <el-option
                            v-for="dict in questionCategoryList"
                            :key="dict.questionCategoryId"
                            :label="dict.name"
                            :value="dict.questionCategoryId"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['business:Question:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['business:Question:edit']"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['business:Question:remove']"
                >删除
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['business:Question:export']"
                >导出
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="QuestionList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column type="expand">
                <template #default="{row}">
                    <el-card shadow="never" class="expand-card">
                        <div class="row"><span class="title">题目标题:</span><span
                                class="content">{{ row.title }}</span></div>
                        <div class="row"><span class="title">题目内容:</span><span class="content"
                                                                                   v-html="row.content"></span></div>
                        <div class="row">
                            <el-button type="primary" @click="handleAddAnswer(row)"
                                       v-if="row.questionType!==QuestionTypeEnum.JUDGE">添加
                            </el-button>
                        </div>
                        <div class="row">
                            <el-table :data="row.questionAnswerList">
                                <el-table-column label="选项" type="index" width="120"/>
                                <el-table-column label="答案" prop="answer"/>
                                <el-table-column label="是否答案" prop="isAnswer">
                                    <template #default="{row}">
                                        <el-switch @change="handleChangeIsAnswer($event,row)"
                                                   v-model="row.isAnswer"/>
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                                    <template #default="scope">
                                        <el-button link type="primary" icon="Edit"
                                                   @click="handleUpdateAnswer(scope.row)"
                                                   v-hasPermi="['business:QuestionAnswer:edit']">修改
                                        </el-button>
                                        <!--                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"-->
                                        <!--                               v-hasPermi="['business:QuestionAnswer:remove']">删除-->
                                        <!--                    </el-button>-->
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-card>
                </template>
            </el-table-column>
            <el-table-column label="题目编号" align="center" prop="questionId"/>
            <el-table-column label="题目标题" align="center" prop="title"/>
            <!--            <el-table-column label="题目内容" align="center" prop="content"/>-->
            <el-table-column label="题目难度" align="center" prop="lv">
                <template #default="{row}">
                    <el-rate disabled :model-value="row.lv"/>
                </template>
            </el-table-column>
            <el-table-column label="题目分数" align="center" prop="score"/>
            <el-table-column label="题目类型" align="center" prop="questionType">
                <template #default="scope">
                    <dict-tag :options="business_question_type" :value="scope.row.questionType"/>
                </template>
            </el-table-column>
            <el-table-column label="题目分类" align="center" prop="questionCategoryId">
                <template #default="{row}">
                    <span>{{
                        questionCategoryList?.find(x => x.questionCategoryId === row.questionCategoryId)?.name || "默认分类"
                        }}</span>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                               v-hasPermi="['business:Question:edit']">修改
                    </el-button>
                    <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
                               v-hasPermi="['business:Question:remove']">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改题目对话框 -->
        <el-dialog :title="title" v-model="open" width="80vw" append-to-body>
            <el-form ref="QuestionRef" :model="form" :rules="rules" label-width="80px">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="题目类型" prop="questionType">
                            <el-select @change="handleChangeQuestionType" v-model="form.questionType"
                                       placeholder="题目类型">
                                <el-option
                                        v-for="dict in business_question_type"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="题目分类" prop="questionCategoryId">
                            <el-select v-model="form.questionCategoryId" placeholder="题目分类" clearable>
                                <el-option
                                        v-for="dict in questionCategoryList"
                                        :key="dict.questionCategoryId"
                                        :label="dict.name"
                                        :value="dict.questionCategoryId"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="题目分数" prop="score">
                            <el-input-number :min="0" :max="100" v-model="form.score" placeholder="题目分数"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="题目难度" prop="lv">
                            <el-input-number :min="0" :max="5" v-model="form.lv" placeholder="题目难度"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="题目标题" prop="title">
                    <el-input v-model="form.title" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
                <el-form-item label="题目内容">
                    <editor v-model:fileList="form.fileList" v-model="form.content"
                            :biz-type="FileBizTypeEnum.QUESTION_IMAGE"
                            :min-height="192"/>
                </el-form-item>
                <el-form-item prop="answer" label="题目答案"
                              v-if="form.questionAnswerList && form.questionAnswerList.length>0">
                    <el-card shadow="never" class="ff">
                        <el-row :gutter="10" v-for="(answer,index) in form?.questionAnswerList || []" :key="answer._id"
                                style="margin-bottom: 20px">
                            <el-col :span="form.questionType===QuestionTypeEnum.QUESTION?24:8">
                                <el-form-item
                                        v-if="form.questionType===QuestionTypeEnum.SINGLE_CHOICE
                                        ||form.questionType===QuestionTypeEnum.MULTIPLE_CHOICE
                                        ||form.questionType===QuestionTypeEnum.JUDGE"
                                        :label="`选项${index+1}`">
                                    <el-input v-model="answer.answer" type="textarea"
                                              :placeholder="`请输入选项${index+1}的答案`"/>
                                </el-form-item>
                                <el-form-item v-if="form.questionType===QuestionTypeEnum.FILL"
                                              :label="`填空${index+1}`">
                                    <el-input v-model="answer.answer" type="textarea"
                                              :placeholder="`请输入填空${index+1}的答案`"/>
                                </el-form-item>
                                <el-form-item v-if="form.questionType===QuestionTypeEnum.QUESTION">
                                    <el-input class="ff" v-model="answer.answer" type="textarea"
                                              :placeholder="`请输入答案`"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="4"
                                    v-if="form.questionType!==QuestionTypeEnum.FILL && form.questionType!==QuestionTypeEnum.QUESTION">
                                <el-form-item label="是否答案">
                                    <el-switch v-model="answer.isAnswer"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="4"
                                    v-if="form.questionType!==QuestionTypeEnum.JUDGE && form.questionType!==QuestionTypeEnum.QUESTION">
                                <el-form-item>
                                    <el-button v-if="index+1===form.questionAnswerList.length"
                                               @click="handleAddAnswerOption" plain type="success">添加
                                    </el-button>
                                    <el-button v-if="form.questionAnswerList.length>1"
                                               @click="handleRemoveAnswerOption(answer._id)" plain type="danger">删除
                                    </el-button>
                                </el-form-item>
                            </el-col>
                        </el-row>

                    </el-card>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>


        <!--添加或修改答案对话框-->
        <el-dialog :title="answerDialog.title" v-model="answerDialog.open" width="700" append-to-body>
            <el-form ref="QuestionAnswerRef" :model="answerForm" :rules="answerRules">
                <el-form-item label="答案" prop="answer">
                    <el-input type="textarea" v-model="answerForm.answer"/>
                </el-form-item>
                <el-form-item label="是否答案" prop="isAnswer">
                    <el-switch v-model="answerForm.isAnswer"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitAnswerForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>


    </div>
</template>

<script setup name="Question">
import FileBizTypeEnum from "@/enum/FileBizTypeEnum.js";

import {
    listQuestion,
    getQuestion,
    delQuestion,
    addQuestion,
    updateQuestion
} from "@/api/business/Question";
import {allListQuestionCategory} from "@/api/business/QuestionCategory.js";
import {nanoid} from 'nanoid'
import {addQuestionAnswer, getQuestionAnswer, updateQuestionAnswer} from "@/api/business/QuestionAnswer.js";
import QuestionTypeEnum from "@/enum/QuestionTypeEnum.js";

const {proxy} = getCurrentInstance();
const {business_question_type} = proxy.useDict('business_question_type');
const QuestionList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const questionCategoryList = ref([]);
const answerDialog = ref({
    title: "",
    open: false
})

/**
 * 检查填写的答案
 * @param rule
 * @param value
 * @param callback
 */
const checkAnswer = (rule, value, callback) => {
    const opts = form.value.questionAnswerList;
    const questionType = form.value.questionType;

    // 如果是填空题或者问答题
    if (questionType === QuestionTypeEnum.FILL || questionType === QuestionTypeEnum.QUESTION) {
        opts.forEach(opt => {
            opt.isAnswer = true
        })
    }

    if (opts.length === 0 || opts.some(v => !v.answer))
        return callback(new Error('请完善题目答案'))

    if (!opts.some(v => v.isAnswer))
        return callback(new Error('必须有1个选项为答案'))

    // 如果是选择题或者判断题
    if (questionType === QuestionTypeEnum.SINGLE_CHOICE || questionType === QuestionTypeEnum.JUDGE) {
        const length = opts.filter(v => v.isAnswer).length
        length > 1 && callback(new Error('只能1个允许为答案'))
    }
    callback();


}
const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        content: null,
        lv: null,
        score: null,
        questionType: null,
        questionCategoryId: null,
    },
    rules: {
        title: [
            {required: true, message: "题目标题不能为空", trigger: "blur"}
        ],
        lv: [
            {required: true, message: "题目难度不能为空", trigger: "blur"},
        ],
        score: [
            {required: true, message: "题目分数不能为空", trigger: "blur"}
        ],
        questionType: [
            {required: true, message: "题目类型不能为空", trigger: "change"}
        ],
        questionCategoryId: [
            {required: true, message: "题目分类不能为空", trigger: "change"}
        ],
        answer: [
            {required: true, validator: checkAnswer, trigger: "blur"}
        ]
    }
});
const answerData = reactive({
    answerForm: {},
    answerRules: {
        answer: [
            {required: true, message: "答案内容不能为空", trigger: "blur"}
        ]
    }
})
const {answerForm, answerRules} = toRefs(answerData)
const {queryParams, form, rules} = toRefs(data);

/**
 * 选择题目类型
 */
const handleChangeQuestionType = (value) => {
    form.value.questionAnswerList.length = 0;
    switch (value) {
        // 单选 多选 填空
        case QuestionTypeEnum.SINGLE_CHOICE:
        case QuestionTypeEnum.MULTIPLE_CHOICE:
        case QuestionTypeEnum.FILL:
            form.value.questionAnswerList.push({
                _id: nanoid(),
                answer: "",
                isAnswer: false
            })
            break;
        // 判断
        case QuestionTypeEnum.JUDGE:
            form.value.questionAnswerList.push({
                _id: nanoid(),
                answer: "正确",
                isAnswer: false
            }, {
                _id: nanoid(),
                answer: "错误",
                isAnswer: false
            })
            break;
        // 问答
        case QuestionTypeEnum.QUESTION:
            form.value.questionAnswerList.push({
                _id: nanoid(),
                answer: "",
                isAnswer: true
            })
            break;
    }
}
/**
 * 添加答案选项
 */
const handleAddAnswerOption = () => {
    form.value.questionAnswerList.push({
        _id: nanoid(),
        answer: "",
        isAnswer: false
    })
}
/**
 * 移除答案选项
 * @param id 唯一标识
 */
const handleRemoveAnswerOption = (id) => {
    const index = form.value.questionAnswerList.findIndex(x => x._id === id)
    index !== -1 && form.value.questionAnswerList.splice(index, 1);
}

/** 查询题目列表 */
function getList() {
    loading.value = true;
    listQuestion(queryParams.value).then(response => {
        QuestionList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}

/**
 * 获取所有题目类型
 */
const getQuestionCategoryList = () => {
    allListQuestionCategory().then(res => {
        questionCategoryList.value = res.data;
    })
}

// 取消按钮
function cancel() {
    open.value = false;
    answerDialog.value.open = false;
    reset();
    resetQuestionAnswer(null)
}

// 更新答案状态
const handleChangeIsAnswer = (value, row) => {
    row.isAnswer = value;
    updateQuestionAnswer(row).then(response => {
        proxy.$modal.msgSuccess("修改成功");
    });
}

// 表单重置
function reset() {
    form.value = {
        questionId: null,
        title: null,
        content: null,
        lv: 0,
        score: 0,
        questionType: null,
        questionCategoryId: null,
        questionAnswerList: [],
        fileList: []
    };
    proxy.resetForm("QuestionRef");
}

/**
 * 重置答案表单
 */
function resetQuestionAnswer(questionId) {
    answerForm.value = {
        questionAnswerId: null,
        questionId,
        answer: "",
        isAnswer: false
    }
    proxy.resetForm("QuestionAnswerRef");
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.questionId);
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加题目";
}

/**
 * 新增答案
 */
function handleAddAnswer(row) {
    resetQuestionAnswer(row.questionId);
    answerDialog.value.open = true;
    answerDialog.value.title = "添加题目答案"
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const _questionId = row.questionId || ids.value
    getQuestion(_questionId).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改题目";
    });
}

/**
 * 修改答案操作
 */
function handleUpdateAnswer(row) {
    resetQuestionAnswer(row.questionId);
    const _questionAnswerId = row.questionAnswerId;
    getQuestionAnswer(_questionAnswerId).then(response => {
        answerForm.value = response.data;
        answerDialog.value.open = true;
        answerDialog.value.title = "修改题目答案"
    })
}

/**
 * 提交答案表单
 */
function submitAnswerForm() {
    proxy.$refs["QuestionAnswerRef"].validate(valid => {
        if (valid) {
            if (answerForm.value.questionAnswerId != null) {
                updateQuestionAnswer(answerForm.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    answerDialog.value.open = false;
                    getList();
                });
            } else {
                addQuestionAnswer(answerForm.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    answerDialog.value.open = false;
                    getList();
                });
            }
        }
    })

}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["QuestionRef"].validate(valid => {
        if (valid) {
            if (form.value.questionId != null) {
                updateQuestion(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addQuestion(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _questionIds = row.questionId || ids.value;
    proxy.$modal.confirm('是否确认删除题目编号为"' + _questionIds + '"的数据项？').then(function () {
        return delQuestion(_questionIds);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {
    });
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download('business/Question/export', {
        ...queryParams.value
    }, `Question_${new Date().getTime()}.xlsx`)
}

getList();
getQuestionCategoryList()
</script>
<style scoped lang="scss">
.expand-card {
  .row {
    margin-bottom: 20px;

    .title {
      font-size: 20px;
    }

    .content {
      font-size: 18px;
    }
  }
}
</style>
